package cc.eddic.practice.concurrency.impl;

import cc.eddic.practice.concurrency.LogItem;
import cc.eddic.practice.concurrency.LogParser;
import lombok.val;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.stereotype.Component;


import java.io.*;
import java.util.*;

@Component
@Qualifier("LogParserWithLoopCxmImpl")
public class LogParserWithLoopCxmImpl implements LogParser {
    @Override
    public Map<String, List<LogItem>> parse(String folderName) {
        Map<String,List<LogItem>> map=new HashMap<>();
        readLogFiles(folderName,map);
        return map;
    }

    public static void readLogFiles(String folderPath,Map<String,List<LogItem>> map) {
        File folder = new File(folderPath);
        for (File file : Objects.requireNonNull(folder.listFiles())) {
            val logItems = new ArrayList<LogItem>();
            if (file.isDirectory()) {
                readLogFiles(file.getAbsolutePath(),map);
            } else if (file.isFile() && file.getName().endsWith(".log")) {
                try (BufferedReader reader = new BufferedReader(new FileReader(file))) {
                    String line;
                    while ((line = reader.readLine()) != null) {
                        LogItem logItem = new LogItemParserCxmImpl().parse(line).orElse(null);
                        logItems.add(logItem);
                        map.put(file.getName(),logItems);
                    }
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
        }


    }




}
